﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace demo
{
    public class HtmlToPDF
    {
        private Document doc = null;
        private PdfWriter writer = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">保存的文件路径</param>
        public HtmlToPDF(string path)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            doc = new Document(PageSize.A4, 10, 10, 20, 10);
            writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.OpenOrCreate));

            doc.Open();
        }

        /// <summary>
        /// 把html和css写入pdf中
        /// </summary>
        /// <param name="html">html模板字符</param>
        /// <param name="cssFile">css文件路径</param>
        public void PutHtml(string html, string cssPath)
        {
            //html和css文件的流
            MemoryStream htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html));
            FileStream cssStream = new FileStream(cssPath, FileMode.Open, FileAccess.Read);

            PutHtmlToPDF(doc, writer, htmlStream, cssStream);
        }

        /// <summary>
        /// 将html代码生成到pdf
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="writer"></param>
        /// <param name="_str"></param>
        private void PutHtmlToPDF(Document doc, PdfWriter writer, Stream htmlStream, Stream cssStream)
        {
            XMLWorkerHelper xmlHepler = XMLWorkerHelper.GetInstance();
            xmlHepler.ParseXHtml(writer, doc, htmlStream, cssStream, Encoding.UTF8, new SongFontFactory());
        }

        /// <summary>
        /// 新开一页
        /// </summary>
        public void NewPage()
        {
            doc.NewPage();
        }

        /// <summary>
        /// 释放doc的资源
        /// </summary>
        public void Close()
        {
            //关闭文档
            doc.Close();
        }

        /// <summary>
        /// 重写iTextSharp字体(仅仅使用宋体)
        /// </summary>
        public class SongFontFactory : IFontProvider
        {
            public Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color)
            {
                BaseFont bf3 = BaseFont.CreateFont(@"c:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font fontContent = new Font(bf3, size, style, color);
                return fontContent;
            }
            public bool IsRegistered(string fontname)
            {
                return false;
            }
        }
    }
}